import axios from "axios";
import { useTokenStore } from "@/stores/token";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import {useUserStore} from "@/stores/user.js";

const service = axios.create({
    baseURL: import.meta.env.VITE_SERVER_ADDR,
});

//Axios的请求的拦截器
service.interceptors.request.use(function (req) {
    const tokenStore = useTokenStore();
    if (tokenStore.tokenStr) {
        //如果不是登录请求就要在请求头中添加token
        req.headers.token = tokenStore.tokenStr;
    }
    return req;
}, function (error) {
    return Promise.reject(error);
});
//响应拦截器
service.interceptors.response.use(resp => {
    //刷新token
    const token = resp.headers.token;
    if(token){
        const tokenStore = useTokenStore();
        const userStore = useUserStore();
        tokenStore.update(token);
    }
    return resp.data;
}, error => {
    if (error.status == 403) {
        ElMessage.error({
            message: '令牌错误，请重新登陆',
            duration: 1200,
            onClose: () => {//提示信息消失时的回调
                //删除sessionStorage
                const tokenStore = useTokenStore();
                const userStore = useUserStore();
                tokenStore.$reset();
                userStore.$reset()
                let currentPath = router.currentRoute.value.path;
                if (currentPath.startsWith("/admin")) {
                    router.push('/admin/login');
                } else {
                    router.push('/user/login');
                }
            }
        });
    }
});
export default service;